package com.lt.lumentracks.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lt.lumentracks.entity.po.Follow;
import com.lt.lumentracks.entity.po.User;
import com.lt.lumentracks.entity.vo.common.PageVO;
import com.lt.lumentracks.entity.vo.common.Result;
import com.lt.lumentracks.entity.vo.user.UserVO_follow;
import com.lt.lumentracks.mapper.FollowMapper;
import com.lt.lumentracks.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lt.lumentracks.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 关注表 服务实现类
 * </p>
 *
 * @author swl
 * @since 2025-09-03
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Autowired
    private FollowMapper followMapper;
    @Autowired
    private IUserService iUserService;

    // 关注或取关
    @Override
    public Result<Void> follow(Integer userId, Integer followUserId, Boolean isFollow) {
        // 1.判断是关注还是取关
        if (isFollow) {
            // 2.关注-->新增数据
            // 2.1查看关注人数是否达到上限1000人
            long count = count(new LambdaQueryWrapper<Follow>().eq(Follow::getUserId, userId));
            if (count >= 1000) {
                return Result.error("关注人数已达到上限");
            }

            // 2.2.关注表新增
            Follow f = new Follow();
            f.setUserId(userId);
            f.setFollowUserId(followUserId);
            f.setCreateTime(LocalDateTime.now());
            save(f);

            // 2.3.用户表更新
            iUserService.update(new LambdaUpdateWrapper<User>()
                    .eq(User::getId, userId)
                    .setSql("following_count = following_count + 1"));
            iUserService.update(new LambdaUpdateWrapper<User>()
                    .eq(User::getId, followUserId)
                    .setSql("followers_count = followers_count + 1"));
        }else {
            // 3.取关-->删除数据
            // 3.1.用户表更新
            iUserService.update(new LambdaUpdateWrapper<User>()
                    .eq(User::getId, userId)
                    .setSql("following_count = following_count - 1"));
            iUserService.update(new LambdaUpdateWrapper<User>()
                    .eq(User::getId, followUserId)
                    .setSql("followers_count = followers_count - 1"));

            LambdaQueryWrapper<Follow> lqw = new LambdaQueryWrapper<Follow>()
                    .eq(Follow::getUserId, userId)
                    .eq(Follow::getFollowUserId, followUserId);
            remove(lqw); // 3.2.删除数据
        }

        return Result.success();
    }


    // 查询是否关注了某用户
    @Override
    public Result<Boolean> isFollow(Integer userId, Integer followUserId) {
        LambdaQueryWrapper<Follow> lqw = new LambdaQueryWrapper<Follow>()
                .eq(Follow::getUserId, userId)
                .eq(Follow::getFollowUserId, followUserId);
        long count = count(lqw);
        return Result.success(count > 0);
    }


    // 查询我的关注
    @Override
    public PageVO<UserVO_follow> getFollows(Integer userId, Integer pageNum, Integer pageSize) {
        // 1.分页查询
        Page<Follow> page_mp = lambdaQuery()
                .eq(Follow::getUserId, userId)
                .orderByDesc(Follow::getCreateTime)
                .page(Page.of(pageNum, pageSize));
        if(page_mp.getTotal() < 1){
            return new PageVO<>(0L,0L, List.of());
        }
        if(page_mp.getRecords().isEmpty()){
            return new PageVO<>(page_mp.getTotal(), page_mp.getPages(), List.of());
        }

        // 2.封装UserVO_follow
        // 2.1.提取（我关注的）用户id列表
        List<Integer> f_userIdList = page_mp.getRecords().stream().map(Follow::getFollowUserId).toList();

        // 2.2.提取关注时间
        Map<Integer, LocalDateTime> followTimeMap = page_mp.getRecords().stream().collect(Collectors.toMap(Follow::getFollowUserId, Follow::getCreateTime));

        // 2.3.筛选出互关的好友（从关注的人中筛选）
        List<Integer> mutualFriendsIds = getMutualFriendsIds_follow(userId, f_userIdList);

        // 2.4.转换为 UserVO_follow， 注意要按原顺序返回，所以要用 f_userIdList 作为流
        Map<Integer, User> userMap = iUserService.listByIds(f_userIdList).stream().collect(Collectors.toMap(User::getId, u -> u));
        List<UserVO_follow> voList = f_userIdList.stream()
                .map(userMap::get)  // 2.4.1.取出对应的 User 对象
                .map(user -> {  // 2.4.2.把 User 转换成 UserVO_follow
                    UserVO_follow uvo = new UserVO_follow();
                    BeanUtils.copyProperties(user, uvo);
                    uvo.setFollowCreateTime(followTimeMap.get(user.getId()));
                    uvo.setMutualFollow(mutualFriendsIds.contains(user.getId()));
                    return uvo;
                })
                .collect(Collectors.toList());

        // 3.返回数据
        PageVO<UserVO_follow> vo = new PageVO<>();
        vo.setTotal(page_mp.getTotal());
        vo.setPages(page_mp.getPages());
        vo.setList(voList);
        return vo;
    }

    // 查询我的关注--根据用户名字模糊查询
    @Override
    public PageVO<UserVO_follow> getFollowsByName(Integer userId, String followName, Integer pageNum, Integer pageSize) {
        // 1.分页查询
        Page<User> page = new Page<>(pageNum, pageSize);
        IPage<User> page_res = followMapper.selectUserByFollowAndName(followName, userId, page);

        // 2.转换数据（封装UserVO_follow）
        // 2.1.提取（我关注的）用户id列表
        List<Integer> f_userIdList = page_res.getRecords().stream().map(User::getId).toList();

        // 2.2.筛选出互关的好友（从关注的人中筛选）
        List<Integer> mutualFriendsIds = getMutualFriendsIds_follow(userId, f_userIdList);

        // 2.3.将 User 转换为 UserVO_follow，注意要按原顺序返回，所以要用 f_userIdList 作为流
        Map<Integer, User> userMap = iUserService.listByIds(f_userIdList).stream().collect(Collectors.toMap(User::getId, u -> u));
        List<UserVO_follow> voList = f_userIdList.stream()
                .map(userMap::get)
                .map(user -> {
                    UserVO_follow uvo = new UserVO_follow();
                    BeanUtils.copyProperties(user, uvo);
                    uvo.setMutualFollow(mutualFriendsIds.contains(user.getId()));
                    return uvo;
                })
                .collect(Collectors.toList());

        PageVO<UserVO_follow> vo = new PageVO<>();
        vo.setTotal(page_res.getTotal());
        vo.setPages(page_res.getPages());
        vo.setList(voList);
        return vo;
    }

    // 查询我的粉丝
    @Override
    public PageVO<UserVO_follow> getFans(Integer userId, Integer pageNum, Integer pageSize) {
        // 1.分页查询
        Page<Follow> page_mp = lambdaQuery()
                .eq(Follow::getFollowUserId, userId)
                .orderByDesc(Follow::getCreateTime)
                .page(Page.of(pageNum, pageSize));
        if(page_mp.getTotal() < 1){
            return new PageVO<>(0L,0L, List.of());
        }
        if(page_mp.getRecords().isEmpty()){
            return new PageVO<>(page_mp.getTotal(), page_mp.getPages(), List.of());
        }

        // 2.封装UserVO_follow
        // 2.1.提取粉丝们的id列表
        List<Integer> f_userIdList = page_mp.getRecords().stream().map(Follow::getUserId).toList();

        // 2.2.提取粉丝们的关注时间
        Map<Integer, LocalDateTime> followTimeMap = page_mp.getRecords().stream().collect(Collectors.toMap(Follow::getUserId, Follow::getCreateTime));

        // 2.3.筛选出互关的好友（查询我关注了粉丝中的谁）
        List<Integer> mutualFriendsIds = getMutualFriendsIds_fans(userId, f_userIdList);

        // 2.4.转换为 UserVO_follow， 注意要按原顺序返回，所以要用 f_userIdList 作为流
        Map<Integer, User> userMap = iUserService.listByIds(f_userIdList).stream().collect(Collectors.toMap(User::getId, u -> u));
        List<UserVO_follow> voList = f_userIdList.stream()
                .map(userMap::get)  // 2.4.1.取出对应的 User 对象
                .map(user -> {  // 2.4.2.把 User 转换成 UserVO_follow
                    UserVO_follow uvo = new UserVO_follow();
                    BeanUtils.copyProperties(user, uvo);
                    uvo.setFollowCreateTime(followTimeMap.get(user.getId()));
                    uvo.setMutualFollow(mutualFriendsIds.contains(user.getId()));
                    return uvo;
                })
                .collect(Collectors.toList());

        // 3.返回数据
        PageVO<UserVO_follow> vo = new PageVO<>();
        vo.setTotal(page_mp.getTotal());
        vo.setPages(page_mp.getPages());
        vo.setList(voList);
        return vo;
    }




    /** 从关注的用户中，筛选出互关的好友
     * @param userId 当前用户ID
     * @param userIdList 关注的用户ID列表
     * @return 筛选后的用户ID列表
     */
    public List<Integer> getMutualFriendsIds_follow(Integer userId, List<Integer> userIdList) {
        if (userIdList == null || userIdList.isEmpty()) {
            return new ArrayList<>();
        }

        // 1. 批量查询：当前用户(userId) 是否也被 userIdList 中的这些用户关注
        // SELECT * FROM follow WHERE user_id IN #{userIdList} AND follow_user_id = #{userId};
        LambdaQueryWrapper<Follow> lqw = new LambdaQueryWrapper<Follow>()
                .in(Follow::getUserId, userIdList) // 关注者是候选列表中的用户
                .eq(Follow::getFollowUserId, userId); // 被关注者是当前用户
        List<Follow> followList = list(lqw); // 执行一次查询

        // 2. 从查询结果中提取出那些关注了当前用户的用户ID (即互关的ID)
        return followList.stream()
                .map(Follow::getUserId)
                .collect(Collectors.toList());
    }


    /** 从粉丝中，筛选出互关的好友
     * @param userId 当前用户ID
     * @param userIdList 粉丝ID列表
     * @return 筛选后的用户ID列表
     */
    public List<Integer> getMutualFriendsIds_fans(Integer userId, List<Integer> userIdList) {
        if (userIdList == null || userIdList.isEmpty()) {
            return new ArrayList<>();
        }

        // 1. 批量查询：当前用户(userId) 是否也关注了 userIdList 中的这些用户
        // SELECT * FROM follow WHERE user_id = #{userId} AND follow_user_id IN #{userIdList};
        LambdaQueryWrapper<Follow> lqw = new LambdaQueryWrapper<Follow>()
                .eq(Follow::getUserId, userId) // 关注者是当前用户
                .in(Follow::getFollowUserId, userIdList); // 被关注者是候选列表中的用户
        List<Follow> followList = list(lqw); // 执行一次查询

        // 2. 提取关注的用户的id
        return followList.stream()
                .map(Follow::getFollowUserId)
                .collect(Collectors.toList());
    }

}
